<?php
namespace app\shop\controller;
use app\shop\controller\Common;
use think\Db;
use think\Loader;
use think\Validate;

class Im extends Common{
    //栏目列表
    public function lst(){
        $list = Db::name('chat_message')->order('id asc')->select();
        foreach($list as $key=>&$value){
            $value['headimgurl'] = $this->webconfig['weburl'].'/'.$value['headimgurl'];
        }
        $this->assign('list', $list);
        return $this->fetch();     
    }




    /**
     * 聊天记录
     */
    public function chatlist(){
        $id = input('param.id');
        $mess_token = db('chat_listmessage')->where(['cid'=>$id])->group('token')->column('token');
        if(empty($mess_token)){
            $mess_token = [-1];
        }
        $ids = db('member_token')->where(['token'=>['in',$mess_token]])->column('user_id');
        if(empty($ids)){
            $ids = [-1];
        }
        $member = db('member')->where(['id'=>['in',$ids]])->field('id,user_name,headimgurl,summary')->select();
        foreach($member as $key=>&$value){
            $value['headimgurl'] ? $value['headimgurl'] = $this->webconfig['weburl'].'/'.$value['headimgurl'] : $value['headimgurl'] = $this->webconfig['weburl'].'/uploads/default';
            $member[$key]['token'] = db('member_token')->where(['user_id'=>$value['id']])->value('token');
            $value['summary'] ? $value['summary'] : $value['summary']='这个人很懒，什么都没有写';
        }

        $this->assign([
            'cid'=>$id,
           'member'=>$member,
        ]);
        return $this->fetch();
    }


    /**
     * 获取个人的聊天记录
     */
    public function userChatLog(){
        if(request()->isAjax()){
            $chatToken = input('id');
            $shopToken = session('shopsh_token');

            $chatLog = Db::name('chat_message')->where("((fromid='{$shopToken}' and toid='{$chatToken}') or (fromid='{$chatToken}' and toid='{$shopToken}'))")
                                        ->order('createtime desc')
                                        ->select();

            foreach ($chatLog as $k => $v){
                $memberId = Db::name('member_token')->where('token',$v['fromid'])->value('user_id');
                $chatLog[$k]['from_user'] = Db::name('member')->where('id',$memberId)->find();
                $chatLog[$k]['from_user']['avatar'] = url_format($chatLog[$k]['from_user']['headimgurl'],$this->webconfig['weburl']);
            }

            if( empty($chatLog) ){
                return json( ['code' => 0, 'data' => '', 'msg' => '没有记录'] );
            }

            return json( ['code' => 1, 'data' => $chatLog, 'msg' => 'success'] );

        }else{
            $chatToken = input('id');
            $this->assign('chatToken',$chatToken);
            return $this->fetch();
        }

    }

    //获取列表
    public function getList()
    {
        $shopMember = Db::name('member')->where('shop_id',session('shopsh_id'))->field('id,user_name,headimgurl')->find();

        $return = [
            'code' => 0,
            'msg'=> '',
            'data' => [
                'mine' => [
                    'username' => $shopMember['user_name'],
                    'id' => session('shopsh_token'),
                    'status' => 'online',
                    'sign' => '商家客服',
                    'avatar' => url_format($shopMember['headimgurl'],$this->webconfig['weburl'])
                ],
                'friend' => [
                    [
                        'groupname' => '顾客',
                        'id' => 1,
                        'online' => 0,
                        'list' => []
                    ]
                ],
                'group' => 2
            ],
        ];



        $shopToken = session('shopsh_token');
        $sql = "SELECT * FROM(
                                        SELECT id,message,is_read,usertype,messagetype,createtime,fromid AS F,toid AS T FROM sp_chat_message WHERE fromid='".$shopToken."'
                                        UNION
                                        SELECT id,message,is_read,usertype,messagetype,createtime,toid AS F,fromid AS T FROM sp_chat_message WHERE toid='" .$shopToken."' ORDER BY createtime DESC
                                    ) sp GROUP BY T ORDER BY createtime DESC";
        $chatData = Db::query($sql);
        if($chatData) {

            foreach ($chatData as $key => &$value) {

                $value['fromid'] = $value['F'];
                $value['id'] = $value['toid'] = $value['T'];

                $fromUserId = Db::name('member_token')->where("token",$value['fromid'])->value('user_id');
                $fromUser = Db::name('member')->where("id",$fromUserId)->find();
                $toUserId = Db::name('member_token')->where("token",$value['toid'])->value('user_id');
                $toUser = Db::name('member')->where("id",$toUserId)->find();

                $value['from_username'] = empty($fromUser['user_name']) ? '匿名' : $fromUser['user_name'];
                $value['from_headimgurl'] = url_format($fromUser['headimgurl'],$this->webconfig['weburl']);
                $value['username'] = $value['to_username'] = empty($toUser['user_name']) ? '匿名' : $toUser['user_name'];
                $value['avatar'] = $value['to_headimgurl'] = url_format($toUser['headimgurl'],$this->webconfig['weburl']);
                $value['message_type'] = $value['messagetype'];
                $value['userType'] = $value['usertype'];
                $value['msg_time'] = $value['createtime'];
                $value['dates'] = date('Y-m-d H:i:s',$value['createtime']);
                unset($value['usertype']);

                $value['msg'] = $value['message'];
                $value['msgtype'] = $value['messagetype'];
            }

        }else{
            $chatData = [];
        }

        $return['data']['friend'][0]['list'] = $chatData;

        return json( $return );

    }



}